import {
    Component,
    EventEmitter,
    Output,
    OnInit,
    OnDestroy,
} from '@angular/core';
import {
    AbstractControl,
    FormBuilder,
    FormControl,
    FormGroup,
    Validators,
} from '@angular/forms';
import { Subscription } from 'rxjs';
function isEmptyInputValue(value: any): boolean {
    return value == null || value.length === 0;
}

function isMobile(value: string): boolean {
    return typeof value === 'string' && /(^1\d{10}$)/.test(value);
}
@Component({
    selector: 'app-child-subscription',
    templateUrl: './child-subscription.component.html',
    styleUrls: ['./child-subscription.component.less'],
})
export class ChildSubscriptionComponent implements OnInit {
    @Output() formValidityChanged = new EventEmitter<boolean>(); // 用于向父组件发送表单合规性
    @Output() getChildValue = new EventEmitter<boolean>(); // 用于向父组件发送表单合规性
    private valueChangesSubscription: Subscription;
    private statusChangesSubscription: Subscription;
    validateForm!: FormGroup;

    constructor(private fb: FormBuilder) {}

    // 手机号码校验规则
    mobile(control: AbstractControl): any | null {
        const value = control.value;
        if (isEmptyInputValue(value)) {
            return null;
        }
        return isMobile(value)
            ? null
            : {
                  mobile: {
                      'zh-cn': `手机号码格式不正确`,
                      en: `Mobile phone number is not valid`,
                  },
              };
    }

    ngOnInit(): void {
        this.initForm();
        // 监听表单值变化
        this.valueChangesSubscription =
            this.validateForm.valueChanges.subscribe(() => {
                // this.checkFormValidity(); // 每次表单内容变化时检查合规性
                // 每次表单内容变化时传递内容给父组件
                this.getChildValue.emit(this.validateForm.value);
            });

        // 监听表单状态变化
        this.statusChangesSubscription =
            this.validateForm.statusChanges.subscribe(() => {
                this.checkFormValidity(); // 每次表单状态变化时检查合规性
            });
    }

    ngOnDestroy(): void {
        // 组件销毁时取消订阅
        this.valueChangesSubscription.unsubscribe();
        this.statusChangesSubscription.unsubscribe();
    }

    initForm() {
        this.validateForm = this.fb.group({
            inputForm: [null, [Validators.required]],
            mobile: ['', [this.mobile]],
            email: ['', [Validators.email]],
        });
    }

    // 重置表单
    resetForm(e: MouseEvent): void {
        this.validateForm.reset();
        for (const key in this.validateForm.controls) {
            if (this.validateForm.controls.hasOwnProperty(key)) {
                this.validateForm.controls[key].markAsPristine();
                this.validateForm.controls[key].updateValueAndValidity();
            }
        }
    }

    // 提交表单
    submitForm(): void {
        // 在提交前进行校验是否符合表单规则
        if (this.validateForm.valid) {
            console.log('submit', this.validateForm.value);
        } else {
            alert('表单校验未通过');
        }
    }

    // 检查表单是否有效，并将结果传递给父组件
    checkFormValidity(): void {
        const isFormValid = this.validateForm.valid; // 获取整个表单的有效性
        this.formValidityChanged.emit(isFormValid); // 发射合规性到父组件
    }
}
